import { ResponseCode } from "@/enum/appEnum";

export function isIE() {
  const bw = window.navigator.userAgent;
  const compare = (s: string) => bw.indexOf(s) >= 0;
  const ie11 = (() => "ActiveXObject" in window)();
  return compare("MSIE") || ie11;
}

export function resultFilter(
  result: any,
  options?: { checkStatus?: boolean; checkDatasLength?: boolean }
) {
  const defaultOptions = {
    checkStatus: true,
    checkDatasLength: true,
  };
  const currentOptions = {
    ...defaultOptions,
    ...options,
  };
  let { code, msg, datas } = result;
  if (!code) {
    code = 0;
  }
  if (!msg) {
    msg = "请求失败";
  }
  if (!datas) {
    datas = null;
  }

  const { checkStatus, checkDatasLength } = currentOptions;
  if (checkStatus) {
    if (code !== ResponseCode.success)
      return { ...result, checkStatus: false, code, msg, datas };
    if (!checkDatasLength && code === ResponseCode.success)
      return { ...result, checkStatus: true, code, msg, datas };
  }
  if (checkDatasLength) {
    if (!datas) return { checkStatus: false, code, msg };
    if (datas && Object?.keys(datas)?.length > 0)
      return { ...result, checkStatus: true, code, msg, datas };
  }

  return { ...result, checkStatus: false, code, msg, datas };
}

export const getQueryParameters = (options: { [propName: string]: any }) => {
  const url = options.url;
  const search = url.split("?")[1];
  if (!search) {
    return {};
  }
  return JSON.parse(
    '{"' +
      decodeURIComponent(search)
        .replace(/"/g, '\\"')
        .replace(/&/g, '","')
        .replace(/=/g, '":"') +
      '"}'
  );
};

export const removeProxy = (type: string, data: any) => {
  if(type === "array"){
    if(data && data?.length > 0){
      return JSON.parse(JSON.stringify(data));
    }
    return [];
  }
  if(type === "object"){
    if(data && Object.keys(data)?.length > 0){
      return JSON.parse(JSON.stringify(data));
    }
    return {};
  }
  throw new Error("removeProxy: 没有正确传参");
};

// 防抖
export function debounce(fn: Function, delay = 200) {//fn是需要防抖的函数，delay是延迟多少毫秒执行fn
  let timer: any = null;
  return function () {
    clearTimeout(timer);
  
    timer = setTimeout(() => {
    fn.apply(fn, arguments);
    timer = null; 
  }, delay)
 }
}